<template>
  <div class="login">
    <!-- 登录卡片容器 -->
    <div class="login__card animate__animated animate__fadeIn">
      <!-- 左侧装饰区域 -->
      <div class="login__image">
        <div class="login__decoration"></div>
        <!-- 系统标题区域 -->
        <div class="login__text-overlay">
          <h1 class="login__title">后台管理系统</h1>
          <p class="login__subtitle">Admin Management System</p>
        </div>
        <!-- 装饰图片 -->
        <img
          src="@/assets/svg/login-bg.svg"
          alt="登录装饰图"
          class="login__tech-image animate__animated animate__bounceIn"
        />
      </div>

      <!-- 右侧登录表单区域 -->
      <div class="login__form-container">
        <!-- 标题区域 -->
        <div class="login__header">
          <img
            src="@/assets/logo.svg"
            alt="Logo"
            class="login__logo animate__animated animate__bounceIn"
          />
          <h2 class="login__welcome animate__animated animate__fadeInUp">欢迎登录</h2>
          <p class="login__welcome-text">登录后开启您的精彩之旅</p>
        </div>

        <!-- 登录表单 -->
        <el-form ref="loginFormRef" :model="loginForm" :rules="rules" class="login__form">
          <!-- 用户名输入框 -->
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              placeholder="用户名"
              :prefix-icon="User"
              @keyup.enter="handleLogin(loginFormRef)"
            />
          </el-form-item>

          <!-- 密码输入框 -->
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="密码"
              :prefix-icon="Lock"
              show-password
              @keyup.enter="handleLogin(loginFormRef)"
            />
          </el-form-item>

          <!-- 记住密码和忘记密码 -->
          <div class="login__options">
            <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
            <el-link type="primary" class="login__forgot-pwd">忘记密码？</el-link>
          </div>

          <!-- 登录按钮 -->
          <el-button
            type="primary"
            :loading="loading"
            class="login__button"
            @click="handleLogin(loginFormRef)"
          >
            {{ loading ? '登录中...' : '登 录' }}
          </el-button>
        </el-form>

        <!-- 底部版权信息 -->
        <div class="login__footer">
          <p>© {{ new Date().getFullYear() }} Your Company. All rights reserved.</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
/**
 * 登录页面组件
 *
 * 功能：
 * 1. 用户登录验证
 * 2. 记住用户账号密码
 * 3. 响应式设计
 * 4. 动画效果
 */
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { User, Lock } from '@element-plus/icons-vue'
import { useRouter, useRoute } from 'vue-router'
import { userApi } from '@/api/user'
import { getValidationRules } from '@/utils/componentUtils'
import { addTransition } from '@/utils/animationUtils'
import { useUserStore } from '@/stores/user'
import { encrypt, decrypt } from '@/utils/crypto'
import { normalizeRedirectPath } from '@/utils/routeUtils'
import { ElMessage } from 'element-plus'

/**
 * 表单状态及引用
 */
const loginForm = reactive({
  username: '',
  password: '',
  remember: false,
})

const loading = ref(false)
const loginFormRef = ref(null)

/**
 * 路由和Store实例
 */
const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

/**
 * 表单验证规则
 * 使用通用验证规则工具函数
 */
const rules = {
  username: getValidationRules('username'),
  password: getValidationRules('password'),
}

/**
 * 处理登录逻辑
 * 1. 表单验证
 * 2. 调用登录API
 * 3. 保存记住的登录信息
 * 4. 获取用户信息并存储到store
 * 5. 路由跳转
 *
 * @param {Object} formEl - 表单引用对象
 */
const handleLogin = async (formEl) => {
  if (!formEl) return

  try {
    // 表单验证
    await formEl.validate()
    loading.value = true

    // 调用登录接口
    await userApi.login({
      username: loginForm.username,
      password: loginForm.password,
    })

    ElMessage.success('登录成功')

    // 保存登录信息到本地存储
    saveLoginInfo()

    // 获取并保存用户信息
    const userInfo = await userApi.getCurrentInfo()
    userStore.setUserInfo(userInfo)

    // 路由跳转: 如果有重定向地址则跳转，否则跳转到首页
    const redirect = normalizeRedirectPath(route.query.redirect)
    const targetPath = redirect ? `/${redirect}`.replace(/\/+/g, '/') : '/'
    router.push(targetPath)
  } catch (error) {
    console.error('登录失败:', error)
    ElMessage.error('登录失败，请检查用户名和密码')
  } finally {
    loading.value = false
  }
}

/**
 * 保存登录信息到本地存储
 * 仅在用户选择"记住我"时保存
 */
const saveLoginInfo = () => {
  if (loginForm.remember) {
    try {
      const encryptedPassword = encrypt(loginForm.password)

      const loginInfo = {
        username: loginForm.username,
        password: encryptedPassword,
        remember: true,
      }

      localStorage.setItem('loginInfo', JSON.stringify(loginInfo))
    } catch (encryptError) {
      console.error('密码加密失败:', encryptError)
      localStorage.removeItem('loginInfo')
    }
  } else {
    localStorage.removeItem('loginInfo')
  }
}

/**
 * 加载保存的登录信息
 * 从本地存储中获取并填充到表单
 */
const loadSavedLoginInfo = () => {
  try {
    const savedInfo = localStorage.getItem('loginInfo')
    if (savedInfo) {
      const parsedInfo = JSON.parse(savedInfo)

      loginForm.username = parsedInfo.username
      loginForm.remember = parsedInfo.remember

      // 如果记住密码，则解密并填充密码
      if (parsedInfo.remember && parsedInfo.password) {
        try {
          const decryptedPassword = decrypt(parsedInfo.password)
          loginForm.password = decryptedPassword
        } catch (decryptError) {
          console.error('密码解密失败:', decryptError)
          // 如果解密失败，清除存储的信息
          localStorage.removeItem('loginInfo')
        }
      }
    }
  } catch (error) {
    console.error('读取登录信息失败:', error)
    localStorage.removeItem('loginInfo')
  }
}

/**
 * 组件生命周期钩子
 */
onMounted(() => {
  // 加载保存的登录信息
  loadSavedLoginInfo()

  // 添加登录卡片动画
  const loginCard = document.querySelector('.login__card')
  if (loginCard) {
    const cleanup = addTransition(loginCard, 'fadeIn 0.3s ease')
    onBeforeUnmount(cleanup)
  }
})
</script>

<style lang="scss" scoped>
// 导入主题变量和混合器
@use '@/assets/styles/theme/base.scss' as *;
@use '@/assets/styles/mixins.scss' as *;

/**
 * 登录页面主容器
 * 使用BEM命名规范
 */
.login {
  @include flex-center;
  min-height: 100vh;
  @include gradient-bg($bg-light, $border-light);
  padding: $font-size-medium;
  position: fixed;
  inset: 0;

  /**
   * 登录卡片
   */
  &__card {
    display: flex;
    width: 100%;
    max-width: 900px;
    background: rgba($bg-base, 0.95);
    border-radius: $radius-large;
    @include box-shadow('medium');
    @include glass-effect(rgba($bg-base, 0.95));
    overflow: hidden;
  }

  /**
   * 左侧装饰区域
   */
  &__image {
    flex: 1.2;
    position: relative;
    @include gradient-bg(rgba($color-primary, 0.05), rgba($color-primary, 0.1));
    border-radius: $radius-large 0 0 $radius-large;
    overflow: hidden;
    @include flex-center;
  }

  /**
   * 装饰性网格覆盖层
   */
  &__decoration {
    position: absolute;
    inset: 0;
    opacity: 0.03;
    background-image: linear-gradient(45deg, rgba($color-primary, 0.1) 25%, transparent 25%),
      linear-gradient(-45deg, rgba($color-primary, 0.1) 25%, transparent 25%),
      linear-gradient(45deg, transparent 75%, rgba($color-primary, 0.1) 75%),
      linear-gradient(-45deg, transparent 75%, rgba($color-primary, 0.1) 75%);
    background-size: 20px 20px;
    background-position:
      0 0,
      0 10px,
      10px -10px,
      -10px 0px;
  }

  /**
   * 文字覆盖层
   */
  &__text-overlay {
    position: absolute;
    top: 15%;
    left: 0;
    right: 0;
    text-align: center;
    z-index: 2;
  }

  /**
   * 主标题
   */
  &__title {
    font-size: $font-size-h1;
    margin: 0 0 8px;
    font-weight: 600;
    letter-spacing: 2px;
    background: linear-gradient(135deg, $color-primary, rgba($color-primary, 0.7));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    animation: fadeInDown 1s ease-out;
  }

  /**
   * 副标题
   */
  &__subtitle {
    font-size: $font-size-body;
    color: $text-secondary;
    margin: 0;
    letter-spacing: 1px;
    text-transform: uppercase;
    animation: fadeInUp 1s ease-out 0.3s both;
  }

  /**
   * 技术图片
   */
  &__tech-image {
    width: 75%;
    height: 75%;
    object-fit: contain;
    z-index: 1;
    filter: drop-shadow(0 4px 16px rgba($color-primary, 0.15));
    animation: float 6s ease-in-out infinite;
    margin-top: 80px;
  }

  /**
   * 右侧表单容器
   */
  &__form-container {
    flex: 1;
    padding: $font-size-h2;
    background: $bg-base;
    display: flex;
    flex-direction: column;
  }

  /**
   * 表单头部区域
   */
  &__header {
    text-align: center;
    margin-bottom: $font-size-h2;
  }

  /**
   * Logo
   */
  &__logo {
    width: 80px;
    height: 80px;
    margin-bottom: $font-size-body;
    @include transition(all);

    &:hover {
      transform: rotate(360deg) scale(1.1);
    }
  }

  /**
   * 欢迎标题
   */
  &__welcome {
    font-size: $font-size-h2;
    color: $text-primary;
    margin: 0;
    font-weight: 600;
  }

  /**
   * 欢迎文本
   */
  &__welcome-text {
    margin-top: $font-size-small;
    color: $text-secondary;
    font-size: $font-size-body;
  }

  /**
   * 登录表单
   */
  &__form {
    .el-form-item {
      margin-bottom: $font-size-medium;
    }

    :deep(.el-input) {
      --el-input-height: 48px;

      .el-input__wrapper {
        border-radius: $radius-medium;
        box-shadow: $shadow-light;
        @include transition(all);
        border: 1px solid $border-base;

        &:hover {
          border-color: $color-primary;
          box-shadow: $shadow-base;
        }

        &.is-focus {
          border-color: $color-primary;
          box-shadow: 0 0 0 2px rgba($color-primary, 0.2);
        }
      }
    }
  }

  /**
   * 记住密码和忘记密码选项
   */
  &__options {
    @include flex-between;
    margin: $font-size-medium 0;

    .el-checkbox {
      color: $text-regular;
      @include transition(color);

      &:hover {
        color: $color-primary;
      }
    }
  }

  /**
   * 忘记密码链接
   */
  &__forgot-pwd {
    font-size: $font-size-body;

    &:hover {
      opacity: 0.8;
    }
  }

  /**
   * 登录按钮
   */
  &__button {
    width: 100%;
    height: 48px;
    font-size: $font-size-medium;
    font-weight: 600;
    letter-spacing: 1px;
    border-radius: $radius-medium;
    @include gradient-bg($color-primary, rgba($color-primary, 0.8));
    border: none;
    @include transition(all);

    &:hover:not([disabled]) {
      transform: translateY(-2px);
      box-shadow: 0 8px 15px rgba($color-primary, 0.3);
    }

    &:active:not([disabled]) {
      transform: translateY(0);
    }
  }

  /**
   * 底部版权信息
   */
  &__footer {
    margin-top: auto;
    text-align: center;
    color: $text-secondary;
    font-size: $font-size-small;
    padding: $font-size-body 0;
  }
}

/**
 * 动画定义
 */
@keyframes float {
  0%,
  100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-20px);
  }
}

@keyframes fadeInDown {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/**
 * 响应式适配
 */
@include respond-to('sm') {
  .login {
    padding: $font-size-small;
    @include gradient-bg(rgba($color-primary, 0.1), rgba($color-primary, 0.05));

    &__card {
      flex-direction: column;
      max-width: 95%;
      margin: $font-size-small;
      background: rgba($bg-base, 0.9);
    }

    &__image {
      display: none;
    }

    &__form-container {
      padding: $font-size-h3 $font-size-medium;
      border-radius: $radius-large;
    }

    &__header {
      margin-bottom: $font-size-h3;
    }

    &__logo {
      width: 60px;
      height: 60px;
    }

    &__welcome {
      font-size: $font-size-h3;
    }

    &__options {
      margin: $font-size-body 0;
    }

    &__footer {
      display: none;
    }
  }
}
</style>
